package com.alex.threads;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class RunnableDemo implements Runnable {
    private Thread t;
    private String threadName;
    private static Integer currentindex = 0;
    private static Lock lock = new ReentrantLock();// 锁对象

    public RunnableDemo(String name) {
        threadName = name;
//        System.out.println("Creating " +  threadName );
    }

    public void run() {
        lock.lock();
//        synchronized (currentindex){
//            try {
               this.currentindex++;
                Thread.yield();
//                Thread.sleep(1000);
                this.currentindex++;

                System.out.println(Thread.currentThread() +" "+ this.threadName+": "+currentindex);
//            } catch (InterruptedException e) {
//                System.out.println("error interruptedexception");
//                e.printStackTrace();
//            }finally {
                lock.unlock();
//            }
//        }



//        System.out.println("Running " +  threadName );
//        try {
//            for(int i = 4; i > 0; i--) {
//                System.out.println("Thread: " + threadName + ", " + i);
//                // 让线程睡眠一会
//                Thread.sleep(50);
//            }
//        }catch (InterruptedException e) {
//            System.out.println("Thread " +  threadName + " interrupted.");
//        }
//        System.out.println("Thread " +  threadName + " exiting.");
    }

    public Thread createThread(){
        if (t == null) {
            t = new Thread (this, threadName);
            t.setPriority(Thread.MIN_PRIORITY);
//            t.setDaemon(true);

        }
        return t;
    }
    public void start () {
//        System.out.println("Starting " +  threadName );
        this.createThread();
        t.start ();
    }
}


